import 'package:flutter/material.dart';
import 'package:shoes_shop/api/api.dart';
import 'package:shoes_shop/core/utils.dart';
import 'package:shoes_shop/models/cart_model.dart';
import 'package:shoes_shop/models/shoe_model.dart';

//设置provider
class PublicProviderModel with ChangeNotifier {
  int currentIndex = 0; // 页面index值
  List<ShoeModelData> goodsList = []; //商品列表
  List<CartModelData> cartList = []; // 购物车列表
  double cartTotal = 0; // 购物车总价
  int cartTotalNum = 0; // 购物车数量
  Map userInfo = {
    'openid': null,
    'nickname': null,
    'avatarUrl': null,
    'email': '未设置邮箱',
    'gender': 0,
  };

  // 存储用户信息
  saveUserInfo(dynamic val) {
    userInfo['openid'] = val.uuid;
    userInfo['nickname'] = val.nickName;
    userInfo['avatarUrl'] = val.avatarUrl;
    userInfo['email'] = val.email;
    userInfo['gender'] = val.gender == 'MALE' ? 0 : 1;
    print('userInfo$userInfo');
    notifyListeners();
  }

  // 修改用户信息
  changeUserInfoValue(String valName, dynamic val) {
    userInfo[valName] = val;
    notifyListeners();
  }

  // 清除用户信息
  cleanUserInfo() {
    userInfo = {
      'openid': null,
      'email': '',
      'nickname': null,
      'avatarUrl': null,
      'gender': 0,
    };
    currentIndex = 0;
    notifyListeners();
  }

  // 修改页面index值
  changeIndex(int index) {
    currentIndex = index;
    notifyListeners();
  }

// 获取商品列表
  providerGetGoodsList() async {
    var res = await getGoodsList();
    if (res.code == null) {
      goodsList = res.data;
    } else {
      showToast('获取商品列表失败');
    }
    goodsList = res.data;
    notifyListeners();
  }

  //  获取购物车列表
  providerGetCartList(List<CartModelData> data) {
    cartList = data;
    calculateCartGoodsPrice();
    notifyListeners();
  }

  // 修改购物车商品数量
  changeGoodsNum(int index, int count) {
    cartList[index].count = count;
    calculateCartGoodsPrice();
    notifyListeners();
  }

  // 删除购物车商品
  removeGoods(int index) {
    cartList.removeAt(index); // 删除第index个商品
    calculateCartGoodsPrice();
    notifyListeners();
  }

  // 计算购物车总的商品的价格
  calculateCartGoodsPrice() {
    double _total = 0;
    int _cartTotalNum = 0;
    cartList.forEach((item) {
      _total = _total + item.count * item.shoesInfo[0].price;
      _cartTotalNum = _cartTotalNum + item.count;
    });
    cartTotal = _total;
    cartTotalNum = _cartTotalNum;
  }

  // 清空购物车
  emptyCart() {
    cartList = [];
    cartTotal = 0;
    cartTotalNum = 0;
    notifyListeners();
  }
}
